package com.dji.sdk.self.internal.controller;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.dji.sdk.self.internal.model.Urls;
import com.dji.sdk.self.internal.network.RetrofitUtil;
import com.dji.sdk.self.internal.utils.ToastUtils;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Map;

import dji.common.error.DJIError;
import dji.common.util.CommonCallbacks;
import dji.sdk.base.BaseProduct;
import dji.sdk.products.Aircraft;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;

public class GetUrl {
    //处理注册登录
    private SharedPreferences token;
    private SharedPreferences.Editor editor;
    private String loginToken;
    private long freshTokenAt,accessTokenAt;
    private long now;
    private String name;
    private boolean isLogin;
    private String serialNumber;
    private String streamUrl;
    public interface Callback{
        void onDataChange(String pushUrl);
    }

    private Callback callback = null;

    public void setCallback(Callback callback) {
        this.callback = callback;
    }


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==100){
                getStreamUrl();

            }
        }
    };;
    public GetUrl(Context context){
        token =context.getSharedPreferences("LoginToken", Activity.MODE_PRIVATE);
        now = System.currentTimeMillis()+6000;


        name = token.getString("username",null);
        loginToken = token.getString("loginToken",null);
        freshTokenAt = token.getLong("refreshTokenExpiresAt",0);
        accessTokenAt = token.getLong("accessTokenExpiresAt",0);
        getNumber();

    }

    private void getStreamUrl() {
        Log.i("SendHttp","getSerialNumber:"+serialNumber);
        if(!TextUtils.isEmpty(serialNumber)){
            RetrofitUtil.getInstance().getApi().getLiveStreamUrl(serialNumber,loginToken)
                    .enqueue(new retrofit2.Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                            try {
                                streamUrl = response.body().string();
                                callback.onDataChange(streamUrl);
                                Log.i("GetUrl",streamUrl);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
        }
    }


    private void getNumber(){
        Log.i("SendHttp","getStreamUrl3");
        if(now+6000>freshTokenAt|| TextUtils.isEmpty(loginToken)||loginToken==null){
            ToastUtils.setResultToToast("请登录账号！");
            editor = token.edit();
            editor.putString("login","false");
            editor.putString("loginToken",null);
            isLogin = false;
        }else{
            if(now+60000>accessTokenAt){
                try {
                    refreshToken();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.i("SendHttp","getStreamUrl4");
        BaseProduct product = DJISampleApplication.getProductInstance();

        if (product != null && product.isConnected()) {
            Log.i("SendHttp","product:"+product.isConnected());
            if (product instanceof Aircraft){
                ((Aircraft) product).getFlightController().getSerialNumber(new CommonCallbacks.CompletionCallbackWith<String>() {
                    @Override
                    public void onSuccess(String s) {
                        serialNumber = s;
                        Log.i("StreamUrl","getNumber:"+serialNumber);
//                        Message message = new Message();
//                        message.what = 100;
//                        handler.sendMessage(message);
                        getStreamUrl();
                    }

                    @Override
                    public void onFailure(DJIError djiError) {

                    }
                });
            }


        }



    }
    private void refreshToken() throws IOException {

        RetrofitUtil.getInstance().getApi()
                .getFreshToken(0,loginToken)
                .enqueue(new retrofit2.Callback<ResponseBody>() {
                    @Override
                    public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                        try {
                            String res = response.body().string();
                            Log.i("SendHttp",res);
                            Gson gson = new Gson();
                            Map result = gson.fromJson(res, Map.class);
                            String newAccessToken = (String) result.get("token");
                            // 因为发生了请求，当前时间已经变化，所有重新获取时间
                            long now2 = System.currentTimeMillis();
                            // 保存到 SharedPreferences
                            token.edit()
                                    .putString("loginToken", newAccessToken)
                                    .putLong("refreshTokenExpiresAt", 86400 * 1000 + now2)
                                    .putLong("accessTokenExpiresAt", 9000 * 1000 + now2)
                                    .apply();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {

                    }
                });
    }

}
